﻿using Furion.LinqBuilder;
using Furion.Localization;
using ST.Torch.WebApi.Application.System.Dtos;
using ST.Torch.WebApi.Application.System.Services;
using ST.Torch.WebApi.Core.Entities.System;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;

namespace ST.Torch.WebApi.Application.System
{

    /// <summary>
    /// 系统服务接口
    /// </summary>
    [AppAuthorize]
    public class SYSMenuAppService : IDynamicApiController
	{
		private readonly SYSMenuService _SYSMenuService;
		public SYSMenuAppService(SYSMenuService sYSMenuService)
		{
			_SYSMenuService = sYSMenuService;
		}

        #region CURD
        [HttpPost]
		public async Task<PagedList<SYSMenuListDto>> GetMenuPagedList([FromForm] PageReq req)
		{
			Expression<Func<SYSMenu, bool>> predicate = u => true;
            predicate=predicate.AndIf(!string.IsNullOrEmpty(req.key),u=>u.Title.Contains(req.key));
			
			var dataList= await _SYSMenuService.QueryPageAsync(predicate, req);
			PagedList<SYSMenuListDto> resultList = dataList.Adapt<PagedList<SYSMenuListDto>>();

			return resultList;
		}
        [HttpPost]
        public async Task<SYSMenuListDto> Single([FromForm] Guid Id)
        {
           
           var entity= await _SYSMenuService.SingleAsync(u=>u.Id==Id);
            SYSMenuListDto resultData = entity.Adapt<SYSMenuListDto>();
			return resultData;

        }
        [HttpPost]
		public async Task  Insert([FromForm] SYSMenuDto model)
		{
			SYSMenu entity = model.Adapt<SYSMenu>();
            if (!string.IsNullOrWhiteSpace(entity.PermissionId) && await _SYSMenuService.AnyAsync(u => u.PermissionId == model.PermissionId))
            {
                throw Oops.Oh($"{model.PermissionId} " + L.Text["权限标识已存在"]);
            }
           
            if (entity.ParentId == Guid.Empty)
            {
                entity.CascadeId = entity.Id.ToString().ToLower();
            }
            else
            {
                var ParetEntity = await _SYSMenuService.SingleAsync(u => u.Id == entity.ParentId, false);
                entity.CascadeId = ParetEntity.CascadeId + "." + entity.Id.ToString().ToLower();
            }

            await _SYSMenuService.InsertAsync(entity);
		}
		[HttpPost]
		public async Task Update([FromForm] SYSMenuListDto model)
		{
			
			var entity=await _SYSMenuService.SingleAsync(u => u.Id == model.Id);
			
            if (!string.IsNullOrWhiteSpace(entity.PermissionId)&& entity.PermissionId != model.PermissionId && await _SYSMenuService.AnyAsync(u => u.PermissionId == model.PermissionId))
            {
                throw Oops.Oh($"{model.PermissionId} " + L.Text["权限标识已存在"]);
            }
            entity.Title=model.Title;
			entity.UpdateTime=model.UpdateTime;
			entity.Href=model.Href;
			entity.Icon=model.Icon;
			entity.IsHide=model.IsHide;
            entity.OpenType=model.OpenType;
			entity.Type=model.Type;
			entity.PermissionId = model.PermissionId;
			entity.ParentId=model.ParentId;
            if (entity.ParentId == Guid.Empty)
            {
                entity.CascadeId = model.Id.ToString().ToLower();
            }
            else
            {
                var ParetEntity = await _SYSMenuService.SingleAsync(u => u.Id == model.ParentId, false);
                entity.CascadeId= ParetEntity.CascadeId+"."+ model.Id.ToString().ToLower();
            }

            entity.Sort=model.Sort;
            await _SYSMenuService.UpdateAsync(entity);
		}
		[HttpPost]
		public async Task DeleteAsync([FromForm] Guid Id)
		{
			var entity = await _SYSMenuService.SingleAsync(u => u.Id == Id);
			await _SYSMenuService.DeleteAsync(entity,true);
		}
        [HttpPost]
        public async Task DeleteBatchAsync([FromForm] List<Guid> Ids)
        {
            var entitys = await _SYSMenuService.QueryAsync(u => Ids.Contains(u.Id));
            foreach (var entity in entitys)
            {
                await _SYSMenuService.DeleteAsync(entity, true);
            }
        }

        #endregion
        [HttpPost]
        public async Task UpdateIsHide([FromForm] Guid Id, [FromForm] bool State)
        {

            var entity = await _SYSMenuService.SingleAsync(u => u.Id == Id);
            entity.IsHide = State;
            entity.UpdateTime = DateTime.Now;
            await _SYSMenuService.UpdateAsync(entity);
        }

        /// <summary>
        /// 获取所有菜单信息(不包含app)
        /// </summary>
        /// <returns></returns>
        [HttpPost, NonUnify]
        public async Task<dynamic> GetAllSystemMenu()
        {
           
            Expression<Func<SYSMenu, bool>> expression = x => true;

            var modules = (await _SYSMenuService.QueryAsync(expression)).OrderBy(u=>u.Sort);
            var systemModuleSecurity = modules.Adapt<List<SYSMenuTreeListDto>>();
            return new
            {
                code = 0,
                msg = "",
                count = systemModuleSecurity.Count,
                data = systemModuleSecurity
            };
        }

        /// <summary>
        /// 获取下拉菜单树
        /// </summary>
        /// <returns></returns>
        [HttpGet, NonUnify]
        public async Task<dynamic> GetSelectTreeMenu()
        {
            Expression<Func<SYSMenu, bool>> expression = x => x.Type == MenuTypeEnum.Menu || x.Type == MenuTypeEnum.Page;
            var modules = await _SYSMenuService.QueryAsync(expression);

           
            List<SYSMenuTreeSelectListDto> MenuSecurities = new List<SYSMenuTreeSelectListDto>();
            SYSMenuTreeSelectListDto menuSecurity = new SYSMenuTreeSelectListDto()
            {
                id = new Guid(),
                title = "根目录"
            };
            MenuSecurities.Add(menuSecurity);
            MenuSecurities.AddRange(GetTreeSelectMenus(modules, new Guid()));
            return new
            {
                status = new { code = 200, message = "ok" },
                data = MenuSecurities
            };
        }

        /// <summary>
        /// 循环获取菜单树
        /// </summary>
        /// <param name="systemModules"></param>
        /// <param name="pId"></param>
        /// <returns></returns>
        private List<SYSMenuTreeListDto> GetTreeMenus(List<SYSMenu> systemModules, Guid? pId)
        {
            List<SYSMenuTreeListDto> MenuSecurities = new List<SYSMenuTreeListDto>();
            foreach (var menu in systemModules.FindAll(r => r.ParentId == pId))
            {
                if (menu.Type == MenuTypeEnum.Menu || menu.Type == MenuTypeEnum.Page)
                {
                    var menuSecurity = menu.Adapt<SYSMenuTreeListDto>();
                    menuSecurity.children = GetTreeMenus(systemModules, menu.Id);
                    MenuSecurities.Add(menuSecurity);
                }
            }
            return MenuSecurities;
        }
        /// <summary>
        /// 循环获取菜单树
        /// </summary>
        /// <param name="systemModules"></param>
        /// <param name="pId"></param>
        /// <returns></returns>
        private List<SYSMenuTreeSelectListDto> GetTreeSelectMenus(List<SYSMenu> systemModules, Guid? pId)
        {
            List<SYSMenuTreeSelectListDto> MenuSecurities = new List<SYSMenuTreeSelectListDto>();
            foreach (var menu in systemModules.FindAll(r => r.ParentId == pId))
            {
                if (menu.Type == MenuTypeEnum.Menu || menu.Type == MenuTypeEnum.Page)
                {
                    var menuSecurity = menu.Adapt<SYSMenuTreeSelectListDto>();
                    menuSecurity.children = GetTreeSelectMenus(systemModules, menu.Id);
                    MenuSecurities.Add(menuSecurity);
                }
            }
            return MenuSecurities;
        }
    }

}
